<template>
  <el-form :inline="true" :model="queryMenuForm" class="demo-form-inline">
    <el-form-item label="父级菜单:">
      <el-select
        v-model="queryMenuForm.parent_id"
        clearable
        placeholder="请选择父菜单"
        style="width: 240px"
      >
        <el-option v-for="item in tableData" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item>

    <el-form-item label="菜单名称:">
      <el-input
        v-model="queryMenuForm.name"
        placeholder="请输入菜单名称"
        clearable
        style="width: 200px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
    </el-form-item>
  </el-form>

  <div class="table-header">
    <span class="table-title">菜单列表</span>
    <el-button type="primary" @click="addMenuDialogAction" v-if="actions.includes('createMenu')"
      >添加</el-button
    >
  </div>
  <el-table :data="tableData">
    <el-table-column prop="parent_name" label="父菜单" />
    <el-table-column prop="name" label="菜单名称" />
    <el-table-column prop="path" label="菜单路径" />
    <el-table-column prop="order_num" label="菜单排序" />
    <el-table-column prop="icon" label="菜单图标" />
    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button @click="fetchUpdateMenu(row.id)" v-if="actions.includes('updateMenu')"
          >编辑</el-button
        >
        <el-button @click="fetchDelMenu(row.id)" v-if="actions.includes('delMenu')">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="addMenuDialog" title="添加菜单" width="500">
    <el-form :model="addMenuForm">
      <el-form-item label="菜单级别" :label-width="formLabelWidth">
        <el-select v-model="addMenuForm.level" placeholder="菜单级别">
          <el-option
            v-for="item in menuLevel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-show="addMenuForm.level === 2" label="父级菜单" :label-width="formLabelWidth">
        <el-select
          v-show="addMenuForm.level === 2"
          v-model="addMenuForm.parent_id"
          clearable
          placeholder="请选择父菜单"
        >
          <el-option
            v-for="item in parentMenuList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="菜单名" :label-width="formLabelWidth">
        <el-input v-model="addMenuForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单路径" :label-width="formLabelWidth">
        <el-input v-model="addMenuForm.path" autocomplete="off" />
      </el-form-item>
      <el-form-item label="菜单icon" :label-width="formLabelWidth">
        <el-input v-model="addMenuForm.icon" autocomplete="off" />
      </el-form-item>
    </el-form>
    <el-form-item label="显示顺序" :label-width="formLabelWidth">
      <el-input
        v-model="addMenuForm.order_num"
        autocomplete="off"
        type="number"
        @input="addMenuForm.order_num = Number(addMenuForm.order_num)"
      />
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addMenuDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchAddMenu"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { addMenu, delMenu, listMenu, updateMenu } from '@/api/menu'
import { setRolePermission } from '@/api/role'
import { reactive, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { tr } from 'element-plus/es/locales.mjs'
import { actions } from '@/api/auth'

const addMenuDialog = ref(false)
const initMenuForm = reactive({
  parent_id: null,
  name: '',
  path: '',
  order_num: 0,
  icon: '',
  level: 1
})

const menuLevel = reactive([
  {
    value: 1,
    label: '一级菜单'
  },
  {
    value: 2,
    label: '二级菜单'
  }
])

const disable_parent_menu = () => {}
const addMenuForm = reactive({ ...initMenuForm })

const formLabelWidth = '140px'
const tableData = ref([])
const parentMenuList = ref([])
const queryMenuForm = reactive({
  ...initMenuForm
})
const fetchListMenu = async (params: {
  parent_id?: number
  name?: string
  level?: number
  page: number
  size: number
}) => {
  try {
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) => value !== undefined && value !== '')
    )
    const res = await listMenu(filteredParams)
    return res
  } catch (error) {
    console.error('Failed to fetch user list:', error)
  }
}

const addMenuDialogAction = async () => {
  addMenuDialog.value = true
  try {
    const res = await listMenu({ page: 1, size: 100, level: 1 })
    parentMenuList.value = res.data.data
  } catch (error) {}
}

const fetchAddMenu = async (params: {}) => {
  try {
    const res = await addMenu(addMenuForm)
    if (res.status < 300) {
      ElMessage.success('添加菜单成功')
      addMenuDialog.value = false
      Object.assign(addMenuForm, initMenuForm) //重置表单内容，不然会显示上次的内容
      const res = await fetchListMenu({
        page: 1,
        size: 10,
        name: queryMenuForm.name,
        parent_id: queryMenuForm.parent_id
      })
      tableData.value = res.data.data
    } else {
      ElMessage.error('添加菜单失败111')
    }
  } catch (error) {
    ElMessage.error('添加菜单失败')
  }
}

const fetchDelMenu = async (id: number) => {
  try {
    const res = await delMenu(id)
    if (res.status < 300) {
      ElMessage.success('删除成功')
      const res = await fetchListMenu({
        page: 1,
        size: 10,
        name: queryMenuForm.name,
        parent_id: queryMenuForm.parent_id
      })
      tableData.value = res.data.data
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {}
}

const fetchUpdateMenu = async (id: number, data: {}) => {
  try {
    const res = await updateMenu(id, data)
    if (res.status < 300) {
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {}
}

onMounted(async () => {
  try {
    // 获取菜单列表
    const res = await fetchListMenu({ page: 1, size: 10 })
    if (res && res.data) {
      tableData.value = res.data.data
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  }
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 25px; /* 添加顶部间距 */
}
.demo-form-inline {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}
</style>